package cn.edu.cqut.mdm.core.lookup;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import cn.edu.cqut.mdm.container.InvokableModuleContainer;
import cn.edu.cqut.mdm.container.PublisherDispatcherContainer;
import cn.edu.cqut.mdm.core.GlobalConfigManager;
import cn.edu.cqut.mdm.core.module.RemoteMethod;
import cn.edu.cqut.mdm.core.module.RemoteModuleEntity;
import cn.edu.cqut.mdm.core.publisherdispatcher.PublisherDispatcher;


public class NetworkModuleFinder {
	private static final String CALL_PATH = "command/modules.do";
	public void findModules() {
		String serverUrls = GlobalConfigManager.getInstance().get(GlobalConfigManager.SERVERS);
		if(serverUrls == null) {
			return;
		}
		for(String serverUrl : serverUrls.split(",")) {
			String serverUrl1 = serverUrl;
			if(serverUrl1 == null || serverUrl1.trim().equals("")) {
				continue;
			}
			URL url;
			if(!serverUrl1.startsWith("http://")){
				serverUrl1 = "http://" + serverUrl1;
			}
			if(!serverUrl1.endsWith("/")){
				serverUrl1 = serverUrl1 + "/";
			}
			serverUrl1 = serverUrl1 + CALL_PATH;
			List<RemoteModuleEntity> remoteModuleEntities = null;
			try {
				url = new URL(serverUrl1);
				HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection();
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((InputStream) httpurlconnection.getContent()));
				String json = bufferedReader.readLine();
				json = new String(json.getBytes(), "utf-8");
				System.out.println(json);
				Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
				classMap.put("methods", RemoteMethod.class);
				JsonConfig config = new JsonConfig();
				config.setClassMap(classMap);
				config.setRootClass(RemoteModuleEntity.class);
				config.setIgnoreTransientFields(true);
				remoteModuleEntities = JSONArray.toList(JSONArray.fromObject(json), config);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if(remoteModuleEntities != null) {
				for(RemoteModuleEntity remoteModuleEntity : remoteModuleEntities) {
					PublisherDispatcher publisherDispatcher = PublisherDispatcherContainer.getInstance().getPublisherDispatcher(remoteModuleEntity.getPublisherDispatcherName());
					remoteModuleEntity.setPublisherDispatcher(publisherDispatcher);
					remoteModuleEntity.setUrl(serverUrl);
					InvokableModuleContainer.getInstance().addRemoteModuleEntity(remoteModuleEntity);
				}
			}
		}
	}
}
